import axios, { AxiosError, type Method } from "axios";
import { getLocalToken } from "./auth";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
import { useUserStore } from "@/stores/user";
const service = axios.create({
  baseURL: "https://api-hmzs.itheima.net/tj",
  timeout: 5000,
});
// 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = getLocalToken();
    if (token) {
      config.headers.Authorization = `Bearer ${token}`;
    }
    return config;
  },
  (error) => {
    ElMessage.error(error.response.data.msg);
    return Promise.reject(error);
  }
);
// 响应拦截器
service.interceptors.response.use(
  (response) => {
    return response.data;
  },
  (error) => {
    ElMessage.error(error.response.data.msg);
    // Token 401处理
    // console.dir(error.response.status)
    if (error.response.status === 401) {
      // 1. 跳转到登录
      const router = useRouter();
      router.push("/login");
      // 2. 清空用户数据
      const store = useUserStore();
      store.clearUserInfo();
    }
    return Promise.reject(error);
  }
);

type Data<T> = {
  code: number;
  message: string;
  data: T;
};
// 4. 请求工具函数
const request = <T>(
  url: string,
  method: Method = "get",
  submitData?: object
) => {
  return service.request<T, Data<T>>({
    url,
    method,
    [method.toLowerCase() === "get" ? "params" : "data"]: submitData,
  });
};
export { request };
